﻿using SufeiUtil;
using System;
using System.Drawing;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace OznerOA.Common
{
    public class HttpHelper
    {
        public static string METHOD_GET = "GET";
        public static string METHOD_POST = "POST";
        public static string CONTENT_TYPE_HTML = "text/html";
        public static string CONTENT_TYPE_JSON = "application/x-www-form-urlencoded";

        /// <summary>
        /// 发送PostPayload请求
        /// </summary>
        public static HttpBaseResult HttpPostPayload(string URL, string Cookie,object data)
        {
            SufeiUtil.HttpHelper http = new SufeiUtil.HttpHelper();
            string json = JsonConvert.SerializeObject(data);
            HttpItem item = new HttpItem()
            {
                URL = URL,
                Method = "post",
                Accept = "application/json, text/plain, */*",
                Postdata = json,
                Cookie = Cookie,
                ContentType = "application/json;charset=UTF-8"
            };
            item.Header.Add("Accept-Encoding", "gzip");
            HttpResult result = http.GetHtml(item);
            HttpBaseResult hbr = new HttpBaseResult()
            {
                Code = (int)result.StatusCode,
                Description = result.StatusDescription,
                Html = result.Html,
                Cookie = result.Cookie,
                ResponseUri = result.ResponseUri,
                RedirectUrl = result.RedirectUrl
            };
            return hbr;
        }



        public static HttpBaseResult HttpGetJson(
            string url, string strCookie)
        {
            return HttpRequest(url, METHOD_GET, strCookie, "", PostDataType.String, ResultType.String, null, CONTENT_TYPE_JSON);
        }
        public static HttpBaseResult HttpPostJson(
            string url, string strCookie,
            string postdata)
        {
            return HttpRequest(url, METHOD_POST, strCookie, postdata, PostDataType.String, ResultType.String, null, CONTENT_TYPE_JSON);
        }

        public static HttpBaseResult HttpGetHtml(
            string url,string strCookie)
        {
            return HttpRequest(url, METHOD_GET, strCookie, "", PostDataType.String, ResultType.String, null,CONTENT_TYPE_HTML);
        }
        public static HttpBaseResult HttpGetByteOrImage(
            string url, string strCookie)
        {
            return HttpRequest(url, METHOD_GET, strCookie, "", PostDataType.String, ResultType.Byte, null, CONTENT_TYPE_HTML);
        }
        public static HttpBaseResult HttpPostHtml(
            string url, string strCookie,
            string postdata)
        {
            return HttpRequest(url, METHOD_POST, strCookie, postdata, PostDataType.String, ResultType.String, null, CONTENT_TYPE_HTML);
        }
        public static HttpBaseResult HttpPostByteOrImage(
            string url, string strCookie,
            string postdata)
        {
            return HttpRequest(url, METHOD_POST, strCookie, postdata, PostDataType.String, ResultType.Byte, null, CONTENT_TYPE_HTML);
        }
        /// <summary>
        /// 发送Http请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">请求方式</param>
        /// <param name="strCookie">字符串Cookie</param>
        /// <param name="postdata">Post的参数</param>
        /// <param name="postdataType">Post参数类型</param>
        /// <param name="resultType">结果类型</param>
        /// <param name="postdataByte">PostByte数据，post参数类型为byte时有效</param>
        /// <returns></returns>
        public static HttpBaseResult HttpRequest(
            string url,
            string method,
            string strCookie,
            string postdata,
            PostDataType postdataType,
            ResultType resultType,
            byte[] postdataByte,
            string ContentType)
        {
            SufeiUtil.HttpHelper http = new SufeiUtil.HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,//URL     必需项
                Encoding = null,//编码格式（utf-8,gb2312,gbk）     可选项 默认类会自动识别
                //Encoding = Encoding.Default,
                Method = method,//URL     可选项 默认为Get
                Timeout = 100000,//连接超时时间     可选项默认为100000
                ReadWriteTimeout = 30000,//写入Post数据超时时间     可选项默认为30000
                IsToLower = false,//得到的HTML代码是否转成小写     可选项默认转小写
                Cookie = strCookie,//字符串Cookie     可选项
                UserAgent = "User - Agent: Mozilla / 5.0(Windows NT 10.0; WOW64; Trident / 7.0; rv: 11.0) like Gecko",//用户的浏览器类型，版本，操作系统     可选项有默认值
                Accept = "text/html, application/xhtml+xml, image/jxr, */*",//    可选项有默认值
                ContentType = ContentType,//返回类型    可选项有默认值
                //Referer = url,//来源URL     可选项
                Allowautoredirect = true,//是否根据３０１跳转     可选项
                //CerPath = "",//证书绝对路径     可选项不需要证书时可以不写这个参数
                Connectionlimit = 1024,//最大连接数     可选项 默认为1024
                Postdata = postdata,//Post数据     可选项GET时不需要写
                PostDataType = postdataType,//默认为传入String类型，也可以设置PostDataType.Byte传入Byte类型数据
                //ProxyIp = "192.168.1.105：8015",//代理服务器ID 端口可以直接加到后面以：分开就行了    可选项 不需要代理 时可以不设置这三个参数
                //ProxyPwd = "123456",//代理服务器密码     可选项
                //ProxyUserName = "administrator",//代理服务器账户名     可选项
                ResultType = resultType,//返回数据类型，是Byte还是String
                PostdataByte = postdataByte,//如果PostDataType为Byte时要设置本属性的值System.Text.Encoding.Default.GetBytes("测试一下")
                CookieCollection = new System.Net.CookieCollection(),//可以直接传一个Cookie集合进来
            };
            //得到HTML代码
            HttpResult result = http.GetHtml(item);
            HttpBaseResult hbr = new HttpBaseResult();
            hbr.Code = (int)result.StatusCode;
            hbr.ResponseUri = result.ResponseUri;
            hbr.Description = result.StatusDescription;
            hbr.Cookie = result.Cookie;
            hbr.RedirectUrl = result.RedirectUrl;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                if (resultType == ResultType.String)
                {
                    hbr.Html = result.Html;
                }
                else
                {
                    hbr.Bytes = result.ResultByte;
                    hbr.Image = byteArrayToImage(result.ResultByte);
                }
            }
            return hbr;
        }
        /// <summary>
        /// 字节数组生成图片
        /// </summary>
        /// <param name="Bytes">字节数组</param>
        /// <returns>图片</returns>
        private static Image byteArrayToImage(byte[] Bytes)
        {
            MemoryStream ms = new MemoryStream(Bytes);
            Image outputImg = Image.FromStream(ms);
            return outputImg;
        }
        public static string postDataFormat(params string[] data)
        {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < data.Length;i+=2)
            {
                if(i > 0)
                {
                    sb.Append("&");
                }
                sb.Append(string.Format("{0}={1}",data[i],data[i+1]));
            }
            return sb.ToString();
        }
    }
}
